package com.geyue.common.util;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SmsUtil {

    private static final String HOST = "https://app.cloopen.com:8883";
    private static final String ACCOUNT_SID = "8a216da85a7d6742015aabfb585a1557";
    private static final String ACCOUNT_TOKEN = "aaa19baf5d4d406eb21afe4629f3a2f4";
    private static final String APPID = "8a216da85a7d6742015aabfb59fe155e";

    /**
     * 发送验证码
     *
     * @param mobile
     */
    public static String send(String mobile) {
        try {
            String timestamp = timestamp();
            String sig = ACCOUNT_SID + ACCOUNT_TOKEN + timestamp;
            String signature = MD5.md5(sig).toUpperCase();
            String path = "/2013-12-26/Accounts/" + ACCOUNT_SID + "/SMS/TemplateSMS?sig=" + signature;
            String method = "POST";
            //随机码
            String code = random();

            Map<String, String> querys = new HashMap<String, String>();
            HttpResponse response = HttpUtils.doPost(HOST, path, method, headers(timestamp), querys, bodys(mobile,code));
            //转为Json对象 方便处理
            JSONObject jsonRes = new JSONObject( EntityUtils.toString(response.getEntity()));
            //请求成功
            if("000000".equals(jsonRes.get("statusCode"))){
                return code;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "-1";
    }

    // 生成6位随机数字
    public static String random() {
        int num = 0;
        num = (int) (Math.random() * 1000000);
        while (num < 100000 || !handle(num)) {
            num = (int) (Math.random() * 1000000);
        }
        String code = String.valueOf(num);
        return code;
    }

    public static boolean handle(int n) {
        int[] list = new int[5];
        for (int i = 0; i < 5; i++) {
            list[i] = n % 10;
            n = n / 10;
        }
        for (int i = 0; i < 5; i++) {
            for (int j = i + 1; j < 5; j++) {
                if (list[i] == list[j])
                    return false;
            }
        }
        return true;
    }

    /**
     * 日期格式转换
     * @return
     */
    public static String timestamp(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        return formatter.format(new Date());
    }

    private static Map<String,String> headers(String timestamp){
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept", "application/json");
        headers.put("Content-Type", "application/json;charset=utf-8");
        //Authorization
        String src = ACCOUNT_SID + ":" + timestamp;
        String auth = Base64.encode(src.getBytes());
        headers.put("Authorization", auth);
        return headers;
    }

    private static String bodys(String mobile,String code){
        JSONObject body = new JSONObject();
        body.put("appId", APPID);
        body.put("to", mobile);
        body.put("templateId", "161552");

        JSONArray arr = new JSONArray();
        arr.put(code);
        arr.put(2);
        body.put("datas", arr);
        return body.toString();
    }
}
